//
//  Manager.swift
//  redhouse
//
//  Created by gix on 2024/5/10.
//

import Foundation
import CoreBluetooth
import Flutter
import TLCLock

// 单例
class Manager: NSObject {
    
    static let shared = Manager()

    fileprivate var cache : [String: TLCDevice] = [:]

//    private var centerManager: CBCentralManager!
//    
//    fileprivate var scanArguments: ScanArguments?
//    fileprivate var needStartScan = false
//    
//    fileprivate var callStack = [CBPeripheral: FlutterResult]()
//    
//    var timestamp = Date().timeIntervalSinceNow
//    
//    private override init() {
//        super.init()
//        centerManager = CBCentralManager(delegate: self, queue: .main, options: nil)
//    }
//
   func test() {
       print("Manager test")
   }

    func connect(_ identifier: String, result: @escaping FlutterResult) {
        let timestamp = Date().timeIntervalSince1970
        debugPrint("connect start \(timestamp)")
        guard let uuid = UUID(uuidString: identifier) else {
            result(FlutterError(code: "1000", message: "identifier invalid", details: nil))
            return
        }
        
        let cbs = centerManager.retrievePeripherals(withIdentifiers: [uuid])
        
        if cbs.isEmpty {
            result(FlutterError(code: "1404", message: "identifier invalid", details: nil))
            return
        }
        
        let cb = cbs.first!
        callStack[cb] = result
        centerManager.connect(cb)
    }
}

//extension Manager: CBCentralManagerDelegate {
//
//    func centralManagerDidUpdateState(_ central: CBCentralManager) {
//        if (central.state == .poweredOn) {
//            if (needStartScan) {
//                central.scanForPeripherals(withServices: scanArguments?.services, options: [CBCentralManagerRestoredStateScanOptionsKey: scanArguments?.allowDuplicationKey ?? false])
//                needStartScan = false
//            }
//        }
//    }
//
//    func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) {
//        peripheral.readRSSI()
//        scanArguments?.events(["name": peripheral.name ?? "Unkown", "identifier": peripheral.identifier.uuidString])
//        
//    }
//    
//    func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) {
//        if let result = callStack[peripheral] {
//            debugPrint("did connected \(Date().timeIntervalSince1970 - timestamp)")
//            result("")
//        }
//    }
//    
//    func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, timestamp: CFAbsoluteTime, isReconnecting: Bool, error: (any Error)?) {
//        debugPrint("did disconnect \(peripheral.identifier) \(timestamp) \(isReconnecting)")
//    }
//
//}

extension Manager: FlutterStreamHandler {
        
    func onListen(withArguments arguments: Any?, eventSink events: @escaping FlutterEventSink) -> FlutterError? {
        
//        scanArguments = ScanArguments.from(arguments, events: events)
        
//        if (centerManager.state == .poweredOn) {
//            centerManager.scanForPeripherals(withServices: scanArguments?.services, options: [CBCentralManagerRestoredStateScanOptionsKey: scanArguments?.allowDuplicationKey ?? false])
//        } else {
//            needStartScan = true
//        }
        
        TLCLock.instance.startScan { sd in
            cache[sd.device.identifier] = sd.device
            
            let arr: [String: Any?] = [
                "name": sd.device.name,
                "identifier": sd.device.identifier,
                "RSSI": sd.RSSI,
            ]
            events(arr)
        }
        
        return nil
    }
    
    func onCancel(withArguments arguments: Any?) -> FlutterError? {
        debugPrint("onCancel")
//        scanArguments = nil
//        centerManager.stopScan()
        TLCLock.instance.stopScan()
        return nil
    }
    
}
